import React from 'react'
import { Space } from 'antd'
import {
  ProFormDateRangePicker,
  ProFormDateTimeRangePicker,
} from '@ant-design/pro-form'

export interface ProTimeRangeSeparateProps {
  startTimeName: string
  endTimeName: string
  showTime?: boolean
  showSeconds?: boolean
  format?: string
  placeholder?: [string, string]
  disabled?: boolean
  allowClear?: boolean
  size?: 'small' | 'middle' | 'large'
  label?: string
  required?: boolean
  rules?: any[]
  style?: React.CSSProperties
  className?: string
  width?: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
  transform?: (value: any) => any
  initialValue?: any
}

const ProTimeRangeSeparate: React.FC<ProTimeRangeSeparateProps> = ({
  startTimeName,
  endTimeName,
  showTime = false,
  showSeconds = false,
  format,
  placeholder,
  disabled = false,
  allowClear = true,
  size = 'middle',
  label,
  required = false,
  rules = [],
  style,
  className,
  width = 'xl',
  transform,
  initialValue,
}) => {
  // 设置默认格式
  const getDefaultFormat = () => {
    if (showTime) {
      return showSeconds ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD HH:mm'
    }
    return 'YYYY-MM-DD'
  }

  const timeFormat = format || getDefaultFormat()

  // 默认验证规则
  const defaultRules = required
    ? [{ required: true, message: `请选择${label}` }]
    : []

  const fieldRules = [...defaultRules, ...rules]

  // 自定义转换函数，将范围值转换为开始和结束时间
  const customTransform = (value: any) => {
    if (transform) {
      return transform(value)
    }

    if (value && Array.isArray(value) && value.length === 2) {
      const [startTime, endTime] = value

      // 若仅选日期(YYYY-MM-DD)，自动拼接 00:00:00 与 23:59:59
      if (!showTime && timeFormat === 'YYYY-MM-DD') {
        const formatDate = (d: any) => {
          if (!d) return undefined
          if (typeof d === 'string') return d
          if (d && typeof d.format === 'function') return d.format('YYYY-MM-DD')
          // 兜底：尝试从 Date 推断
          try {
            const date = d instanceof Date ? d : new Date(d)
            const y = date.getFullYear()
            const m = `${date.getMonth() + 1}`.padStart(2, '0')
            const day = `${date.getDate()}`.padStart(2, '0')
            return `${y}-${m}-${day}`
          } catch (e) {
            return String(d)
          }
        }

        const startDateStr = formatDate(startTime)
        const endDateStr = formatDate(endTime)

        return {
          [startTimeName]: startDateStr
            ? `${startDateStr} 00:00:00`
            : startDateStr,
          [endTimeName]: endDateStr ? `${endDateStr} 23:59:59` : endDateStr,
        }
      }

      return {
        [startTimeName]: startTime,
        [endTimeName]: endTime,
      }
    }
    return {}
  }
  return (
    <div style={style} className={className}>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        {/* 时间范围选择器 */}
        {showTime ? (
          <ProFormDateTimeRangePicker
            name={[startTimeName]}
            label={label}
            width={width}
            rules={fieldRules}
            initialValue={initialValue}
            fieldProps={{
              format: timeFormat,
              placeholder: placeholder,
              disabled: disabled,
              allowClear: allowClear,
              size: size,
              showTime: {
                showSecond: showSeconds,
                format: showSeconds ? 'HH:mm:ss' : 'HH:mm',
              },
            }}
            transform={customTransform}
          />
        ) : (
          <ProFormDateRangePicker
            name={[startTimeName]}
            label={label}
            width={width}
            rules={fieldRules}
            initialValue={initialValue}
            fieldProps={{
              format: timeFormat,
              placeholder: placeholder,
              disabled: disabled,
              allowClear: allowClear,
              size: size,
            }}
            transform={customTransform}
          />
        )}
      </Space>
    </div>
  )
}

export default ProTimeRangeSeparate
